package com.leenleda.ips.net;

import android.os.Environment;

import com.leenleda.ips.BaseActivity;
import com.leenleda.ips.MyApplication;
import com.leenleda.ips.entity.BaseEntity;
import com.leenleda.ips.entity.MarqueeEntity;
import com.leenleda.ips.receiver.Constant;
import com.leenleda.ips.receiver.ReceiverMsg;
import com.leenleda.ips.util.FileUtils;
import com.leenleda.ips.util.GsonUtils;
import com.leenleda.ips.util.LogUtils;
import com.leenleda.ips.util.NetUtils;
import com.leenleda.ips.util.UShared;
import com.leenleda.ips.util.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NetInterface {
    private static NetInterface downloadUtil;
    private final OkHttpClient okHttpClient;
//    private final static String port = ":8913";
    private final static String port = ":8080";
    private static final OkHttpClient client = (new OkHttpClient()).newBuilder()
            .readTimeout(500, TimeUnit.MILLISECONDS)
            .build();

    private static String http = "http://";
    private static String deviceInfo = ":1301/api/device-api/getDeviceInfo";

    //http://192.168.1.131:1301/api/device-api/getDeviceInfo

    public static NetInterface GetInstance() {
        if (downloadUtil == null) {
            downloadUtil = new NetInterface();
        }
        return downloadUtil;
    }

    private NetInterface() {
        okHttpClient = new OkHttpClient();
    }


    public void requestDate(String ipStr, BaseEntity info) {
        LogUtils.e("AndServer", "======requestDate====NET_STATE===" + Constant.NET_STATE);
        InetAddress address = NetUtils.getLocalIPAddress();
        LogUtils.e("AndServer", "======requestDate====address===" + address);
        if (address ==null)
            return;
//        if (info.getServiceIp().trim().isEmpty()) {
//            info.setServiceIp(ipStr);
//        }
        String uploadUrl = http + ipStr + deviceInfo;
        LogUtils.e("AndServer", "======requestDate====uploadUrl===" + uploadUrl);
        LogUtils.e("AndServer", "======requestDate=======" + info);
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("androidid", FileUtils.getDeviceMac())
                .addFormDataPart("packagename", info.getPackageName())
                .addFormDataPart("versioncode", info.getVersionCode() + "")
                .addFormDataPart("ipaddress", address.getHostAddress())
                .addFormDataPart("macaddress", FileUtils.getDeviceMac())
                .addFormDataPart("versionname", info.getPackageName())
                .addFormDataPart("devicemodel", android.os.Build.MODEL)
//                .addFormDataPart("devicename", info.getDeviceName())
                .build();
        Request request = new Request.Builder()
                .url(uploadUrl) // 上传地址
                .post(body)
                .build();

//        info.setHistoryNum(info.getHistoryNum() - 1);
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                UShared.putString(Constant.SET_INPUT_IP, ipStr);
                LogUtils.e("AndServer", "----e-----" + e);
                AEvent.notifyListener(AEvent.NET_REQUEST, false, e.getMessage());
//                EventBus.getDefault().post(new SourceEvent("request_data", -1, e.getMessage()));
                UShared.putString(Constant.WEB_LOAD_GET, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                UShared.putString(Constant.SET_INPUT_IP, ipStr);
                String data = response.body().string();
                UShared.putString(Constant.WEB_LOAD_GET, data);
//                boolean te = BaseUtils.setDeviceInfo(info);
//                ILog.e("AndServer", "--Base---==deviceInfo=-te-" + te);
                LogUtils.e("AndServer", "=----response-------==" + data);
                AEvent.notifyListener(AEvent.NET_REQUEST, response.code() == 200, data);
            }
        });
    }

//    ************************************

    /**
     * @param url      下载连接
     * @param saveDir  储存下载文件的SDCard目录
     */
    public void downLoad(final String url, final String saveDir, final String fileName) {
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) { // 下载失败
                LogUtils.e("downLoad", "=======onFailure========" + e);
                AEvent.notifyListener(AEvent.TO_DOWNLOAD, false, e);
            }
            @Override
            public void onResponse(Call call, Response response) {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
//                    String savePath = isExistDir(saveDir); // 储存下载文件的目录
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(saveDir, fileName);
                    LogUtils.e("downLoad", "=======onResponse===saveDir=====" + saveDir);
//                    ILog.e("downLoad", "=======onResponse===savePath=====" + savePath);
                    LogUtils.e("downLoad", "=======onResponse===fileName=====" + fileName);
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    int progress = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int new_progress = (int) (sum * 1.0f / total * 100);
                        LogUtils.e("downLoad", "=======onResponse===progress=1====" + progress);
                        if (new_progress > progress) {
                            progress = new_progress;
                            LogUtils.e("downLoad", "=======onResponse===progress==2===" + progress);
                            AEvent.notifyListener(AEvent.TO_DOWNLOAD, true, new_progress);
                        }
                    }
                    fos.flush();
                    LogUtils.e("downLoad", "=======onResponse===OK=====" + saveDir);
                    AEvent.notifyListener(AEvent.TO_DOWNLOAD, true, 100);
                } catch (Exception e) {
                    AEvent.notifyListener(AEvent.TO_DOWNLOAD, false, e);
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    /**
     * 判断下载目录是否存在
     */
    private String isExistDir(String saveDir) throws IOException {
        File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
        if (!downloadFile.mkdirs())
            downloadFile.createNewFile();
        String savePath = downloadFile.getAbsolutePath();
        return savePath;
    }

    /**
     * 确认更新工具是否已打开
     */
    public static boolean checkTool() {
        if (BaseActivity.getForegroundActivity() == null)
            return false;
        boolean netState = NetUtils.isNetworkAvailable(BaseActivity.getForegroundActivity());
        if (!netState)
            return false;
        String url = "http://" + Utils.getIPAddress(MyApplication.getInstance()) + port + "/user/checkLive";
        client.connectTimeoutMillis();
        Request request = new Request.Builder().url(url).get().build();
        LogUtils.e("checkTool", "=======checkTool===url===" + url);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                AEvent.notifyListener(AEvent.CHECK_UPDATE_TOOL, false, null);
                LogUtils.e("checkTool", "=======checkTool===onFailure==="  + e);
            }
            @Override
            public void onResponse(Call call, Response response) {
                LogUtils.e("checkTool", "=======checkTool===onResponse==="  + response.code());
                AEvent.notifyListener(AEvent.CHECK_UPDATE_TOOL, response.code() == 200, null);
            }
        });
        return true;
    }

    /**
     * 推送字幕
     */
    public static void pushMsg(MarqueeEntity entity) {
        if (BaseActivity.getForegroundActivity() == null)
            return;
        boolean netState = NetUtils.isNetworkAvailable(BaseActivity.getForegroundActivity());
        if (!netState)
            return;
        LogUtils.e("pushMsg", "======requestDate====NET_STATE===" + Constant.NET_STATE);
        InetAddress address = NetUtils.getLocalIPAddress();
        LogUtils.e("pushMsg", "======requestDate====address===" + address);
        if (address ==null)
            return;
        String scrollStr = GsonUtils.getInstance().toJson(entity);

        String url = "http://" + Utils.getIPAddress(MyApplication.getInstance()) + port + "/user/pushMsg";
        LogUtils.e("pushMsg", "======requestDate====url===" + url);
        LogUtils.e("pushMsg", "======requestDate====scrollStr===" + scrollStr);
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("type", ReceiverMsg.PUSH_NOTICE)
                .addFormDataPart("msgData", scrollStr)
                .build();
        Request request = new Request.Builder().url(url).post(body).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtils.e("pushMsg", "=======pushMsg===onFailure==="  + e);
            }
            @Override
            public void onResponse(Call call, Response response) {
                LogUtils.e("pushMsg", "=======pushMsg===onResponse==="  + response.code());
            }
        });
    }
}

